<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 2.0.16">
<meta name="author" content="Peter Dimov">
<title>Simple C&#43;&#43;11 metaprogramming</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700">
<style>
/*! Asciidoctor default stylesheet | MIT License | https://asciidoctor.org */
/* Uncomment the following line when using as a custom stylesheet */
/* @import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700"; */
html{font-family:sans-serif;-webkit-text-size-adjust:100%}
a{background:none}
a:focus{outline:thin dotted}
a:active,a:hover{outline:0}
h1{font-size:2em;margin:.67em 0}
b,strong{font-weight:bold}
abbr{font-size:.9em}
abbr[title]{cursor:help;border-bottom:1px dotted #dddddf;text-decoration:none}
dfn{font-style:italic}
hr{height:0}
mark{background:#ff0;color:#000}
code,kbd,pre,samp{font-family:monospace;font-size:1em}
pre{white-space:pre-wrap}
q{quotes:"\201C" "\201D" "\2018" "\2019"}
small{font-size:80%}
sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}
sup{top:-.5em}
sub{bottom:-.25em}
img{border:0}
svg:not(:root){overflow:hidden}
figure{margin:0}
audio,video{display:inline-block}
audio:not([controls]){display:none;height:0}
fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}
legend{border:0;padding:0}
button,input,select,textarea{font-family:inherit;font-size:100%;margin:0}
button,input{line-height:normal}
button,select{text-transform:none}
button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}
button[disabled],html input[disabled]{cursor:default}
input[type=checkbox],input[type=radio]{padding:0}
button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}
textarea{overflow:auto;vertical-align:top}
table{border-collapse:collapse;border-spacing:0}
*,::before,::after{box-sizing:border-box}
html,body{font-size:100%}
body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;line-height:1;position:relative;cursor:auto;-moz-tab-size:4;-o-tab-size:4;tab-size:4;word-wrap:anywhere;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased}
a:hover{cursor:pointer}
img,object,embed{max-width:100%;height:auto}
object,embed{height:100%}
img{-ms-interpolation-mode:bicubic}
.left{float:left!important}
.right{float:right!important}
.text-left{text-align:left!important}
.text-right{text-align:right!important}
.text-center{text-align:center!important}
.text-justify{text-align:justify!important}
.hide{display:none}
img,object,svg{display:inline-block;vertical-align:middle}
textarea{height:auto;min-height:50px}
select{width:100%}
.subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em}
div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0}
a{color:#2156a5;text-decoration:underline;line-height:inherit}
a:hover,a:focus{color:#1d4b8f}
a img{border:0}
p{line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility}
p aside{font-size:.875em;line-height:1.35;font-style:italic}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em}
h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0}
h1{font-size:2.125em}
h2{font-size:1.6875em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em}
h4,h5{font-size:1.125em}
h6{font-size:1em}
hr{border:solid #dddddf;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em}
em,i{font-style:italic;line-height:inherit}
strong,b{font-weight:bold;line-height:inherit}
small{font-size:60%;line-height:inherit}
code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)}
ul,ol,dl{line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit}
ul,ol{margin-left:1.5em}
ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0}
ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit}
ul.square{list-style-type:square}
ul.circle{list-style-type:circle}
ul.disc{list-style-type:disc}
ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0}
dl dt{margin-bottom:.3125em;font-weight:bold}
dl dd{margin-bottom:1.25em}
blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd}
blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)}
@media screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2}
h1{font-size:2.75em}
h2{font-size:2.3125em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em}
h4{font-size:1.4375em}}
table{background:#fff;margin-bottom:1.25em;border:1px solid #dedede;word-wrap:normal}
table thead,table tfoot{background:#f7f8f7}
table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left}
table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)}
table tr.even,table tr.alt{background:#f8f8f7}
table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{line-height:1.6}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em}
h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400}
.center{margin-left:auto;margin-right:auto}
.stretch{width:100%}
.clearfix::before,.clearfix::after,.float-group::before,.float-group::after{content:" ";display:table}
.clearfix::after,.float-group::after{clear:both}
:not(pre).nobreak{word-wrap:normal}
:not(pre).nowrap{white-space:nowrap}
:not(pre).pre-wrap{white-space:pre-wrap}
:not(pre):not([class^=L])>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background:#f7f7f8;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed}
pre{color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;line-height:1.45;text-rendering:optimizeSpeed}
pre code,pre pre{color:inherit;font-size:inherit;line-height:inherit}
pre>code{display:block}
pre.nowrap,pre.nowrap pre{white-space:pre;word-wrap:normal}
em em{font-style:normal}
strong strong{font-weight:400}
.keyseq{color:rgba(51,51,51,.8)}
kbd{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background:#f7f7f7;border:1px solid #ccc;border-radius:3px;box-shadow:0 1px 0 rgba(0,0,0,.2),inset 0 0 0 .1em #fff;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap}
.keyseq kbd:first-child{margin-left:0}
.keyseq kbd:last-child{margin-right:0}
.menuseq,.menuref{color:#000}
.menuseq b:not(.caret),.menuref{font-weight:inherit}
.menuseq{word-spacing:-.02em}
.menuseq b.caret{font-size:1.25em;line-height:.8}
.menuseq i.caret{font-weight:bold;text-align:center;width:.45em}
b.button::before,b.button::after{position:relative;top:-1px;font-weight:400}
b.button::before{content:"[";padding:0 3px 0 2px}
b.button::after{content:"]";padding:0 2px 0 3px}
p a>code:hover{color:rgba(0,0,0,.9)}
#header,#content,#footnotes,#footer{width:100%;margin:0 auto;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em}
#header::before,#header::after,#content::before,#content::after,#footnotes::before,#footnotes::after,#footer::before,#footer::after{content:" ";display:table}
#header::after,#content::after,#footnotes::after,#footer::after{clear:both}
#content{margin-top:1.25em}
#content::before{content:none}
#header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0}
#header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #dddddf}
#header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #dddddf;padding-bottom:8px}
#header .details{border-bottom:1px solid #dddddf;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:flex;flex-flow:row wrap}
#header .details span:first-child{margin-left:-.125em}
#header .details span.email a{color:rgba(0,0,0,.85)}
#header .details br{display:none}
#header .details br+span::before{content:"\00a0\2013\00a0"}
#header .details br+span.author::before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)}
#header .details br+span#revremark::before{content:"\00a0|\00a0"}
#header #revnumber{text-transform:capitalize}
#header #revnumber::after{content:"\00a0"}
#content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #dddddf;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem}
#toc{border-bottom:1px solid #e7e7e9;padding-bottom:.5em}
#toc>ul{margin-left:.125em}
#toc ul.sectlevel0>li>a{font-style:italic}
#toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0}
#toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none}
#toc li{line-height:1.3334;margin-top:.3334em}
#toc a{text-decoration:none}
#toc a:active{text-decoration:underline}
#toctitle{color:#7a2518;font-size:1.2em}
@media screen and (min-width:768px){#toctitle{font-size:1.375em}
body.toc2{padding-left:15em;padding-right:0}
#toc.toc2{margin-top:0!important;background:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #e7e7e9;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto}
#toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em}
#toc.toc2>ul{font-size:.9em;margin-bottom:0}
#toc.toc2 ul ul{margin-left:0;padding-left:1em}
#toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em}
body.toc2.toc-right{padding-left:0;padding-right:15em}
body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #e7e7e9;left:auto;right:0}}
@media screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0}
#toc.toc2{width:20em}
#toc.toc2 #toctitle{font-size:1.375em}
#toc.toc2>ul{font-size:.95em}
#toc.toc2 ul ul{padding-left:1.25em}
body.toc2.toc-right{padding-left:0;padding-right:20em}}
#content #toc{border:1px solid #e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;border-radius:4px}
#content #toc>:first-child{margin-top:0}
#content #toc>:last-child{margin-bottom:0}
#footer{max-width:none;background:rgba(0,0,0,.8);padding:1.25em}
#footer-text{color:hsla(0,0%,100%,.8);line-height:1.44}
#content{margin-bottom:.625em}
.sect1{padding-bottom:.625em}
@media screen and (min-width:768px){#content{margin-bottom:1.25em}
.sect1{padding-bottom:1.25em}}
.sect1:last-child{padding-bottom:0}
.sect1+.sect1{border-top:1px solid #e7e7e9}
#content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400}
#content h1>a.anchor::before,h2>a.anchor::before,h3>a.anchor::before,#toctitle>a.anchor::before,.sidebarblock>.content>.title>a.anchor::before,h4>a.anchor::before,h5>a.anchor::before,h6>a.anchor::before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em}
#content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible}
#content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none}
#content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221}
details,.audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em}
details{margin-left:1.25rem}
details>summary{cursor:pointer;display:block;position:relative;line-height:1.6;margin-bottom:.625rem;-webkit-tap-highlight-color:transparent}
details>summary::before{content:"";border:solid transparent;border-left:solid;border-width:.3em 0 .3em .5em;position:absolute;top:.5em;left:-1.25rem;transform:translateX(15%)}
details[open]>summary::before{border:solid transparent;border-top:solid;border-width:.5em .3em 0;transform:translateY(15%)}
details>summary::after{content:"";width:1.25rem;height:1em;position:absolute;top:.3em;left:-1.25rem}
.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic}
table.tableblock.fit-content>caption.title{white-space:nowrap;width:0}
.paragraph.lead>p,#preamble>.sectionbody>[class=paragraph]:first-of-type p{font-size:1.21875em;line-height:1.6;color:rgba(0,0,0,.85)}
.admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%}
.admonitionblock>table td.icon{text-align:center;width:80px}
.admonitionblock>table td.icon img{max-width:none}
.admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase}
.admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #dddddf;color:rgba(0,0,0,.6);word-wrap:anywhere}
.admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0}
.exampleblock>.content{border:1px solid #e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;border-radius:4px}
.exampleblock>.content>:first-child{margin-top:0}
.exampleblock>.content>:last-child{margin-bottom:0}
.sidebarblock{border:1px solid #dbdbd6;margin-bottom:1.25em;padding:1.25em;background:#f3f3f2;border-radius:4px}
.sidebarblock>:first-child{margin-top:0}
.sidebarblock>:last-child{margin-bottom:0}
.sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center}
.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0}
.literalblock pre,.listingblock>.content>pre{border-radius:4px;overflow-x:auto;padding:1em;font-size:.8125em}
@media screen and (min-width:768px){.literalblock pre,.listingblock>.content>pre{font-size:.90625em}}
@media screen and (min-width:1280px){.literalblock pre,.listingblock>.content>pre{font-size:1em}}
.literalblock pre,.listingblock>.content>pre:not(.highlight),.listingblock>.content>pre[class=highlight],.listingblock>.content>pre[class^="highlight "]{background:#f7f7f8}
.literalblock.output pre{color:#f7f7f8;background:rgba(0,0,0,.9)}
.listingblock>.content{position:relative}
.listingblock code[data-lang]::before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:inherit;opacity:.5}
.listingblock:hover code[data-lang]::before{display:block}
.listingblock.terminal pre .command::before{content:attr(data-prompt);padding-right:.5em;color:inherit;opacity:.5}
.listingblock.terminal pre .command:not([data-prompt])::before{content:"$"}
.listingblock pre.highlightjs{padding:0}
.listingblock pre.highlightjs>code{padding:1em;border-radius:4px}
.listingblock pre.prettyprint{border-width:0}
.prettyprint{background:#f7f7f8}
pre.prettyprint .linenums{line-height:1.45;margin-left:2em}
pre.prettyprint li{background:none;list-style-type:inherit;padding-left:0}
pre.prettyprint li code[data-lang]::before{opacity:1}
pre.prettyprint li:not(:first-child) code[data-lang]::before{display:none}
table.linenotable{border-collapse:separate;border:0;margin-bottom:0;background:none}
table.linenotable td[class]{color:inherit;vertical-align:top;padding:0;line-height:inherit;white-space:normal}
table.linenotable td.code{padding-left:.75em}
table.linenotable td.linenos{border-right:1px solid;opacity:.35;padding-right:.5em}
pre.pygments .lineno{border-right:1px solid;opacity:.35;display:inline-block;margin-right:.75em}
pre.pygments .lineno::before{content:"";margin-right:-.125em}
.quoteblock{margin:0 1em 1.25em 1.5em;display:table}
.quoteblock:not(.excerpt)>.title{margin-left:-1.5em;margin-bottom:.75em}
.quoteblock blockquote,.quoteblock p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify}
.quoteblock blockquote{margin:0;padding:0;border:0}
.quoteblock blockquote::before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)}
.quoteblock blockquote>.paragraph:last-child p{margin-bottom:0}
.quoteblock .attribution{margin-top:.75em;margin-right:.5ex;text-align:right}
.verseblock{margin:0 1em 1.25em}
.verseblock pre{font-family:"Open Sans","DejaVu Sans",sans-serif;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility}
.verseblock pre strong{font-weight:400}
.verseblock .attribution{margin-top:1.25rem;margin-left:.5ex}
.quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic}
.quoteblock .attribution br,.verseblock .attribution br{display:none}
.quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)}
.quoteblock.abstract blockquote::before,.quoteblock.excerpt blockquote::before,.quoteblock .quoteblock blockquote::before{display:none}
.quoteblock.abstract blockquote,.quoteblock.abstract p,.quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{line-height:1.6;word-spacing:0}
.quoteblock.abstract{margin:0 1em 1.25em;display:block}
.quoteblock.abstract>.title{margin:0 0 .375em;font-size:1.15em;text-align:center}
.quoteblock.excerpt>blockquote,.quoteblock .quoteblock{padding:0 0 .25em 1em;border-left:.25em solid #dddddf}
.quoteblock.excerpt,.quoteblock .quoteblock{margin-left:0}
.quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{color:inherit;font-size:1.0625rem}
.quoteblock.excerpt .attribution,.quoteblock .quoteblock .attribution{color:inherit;font-size:.85rem;text-align:left;margin-right:0}
p.tableblock:last-child{margin-bottom:0}
td.tableblock>.content{margin-bottom:1.25em;word-wrap:anywhere}
td.tableblock>.content>:last-child{margin-bottom:-1.25em}
table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede}
table.grid-all>*>tr>*{border-width:1px}
table.grid-cols>*>tr>*{border-width:0 1px}
table.grid-rows>*>tr>*{border-width:1px 0}
table.frame-all{border-width:1px}
table.frame-ends{border-width:1px 0}
table.frame-sides{border-width:0 1px}
table.frame-none>colgroup+*>:first-child>*,table.frame-sides>colgroup+*>:first-child>*{border-top-width:0}
table.frame-none>:last-child>:last-child>*,table.frame-sides>:last-child>:last-child>*{border-bottom-width:0}
table.frame-none>*>tr>:first-child,table.frame-ends>*>tr>:first-child{border-left-width:0}
table.frame-none>*>tr>:last-child,table.frame-ends>*>tr>:last-child{border-right-width:0}
table.stripes-all tr,table.stripes-odd tr:nth-of-type(odd),table.stripes-even tr:nth-of-type(even),table.stripes-hover tr:hover{background:#f8f8f7}
th.halign-left,td.halign-left{text-align:left}
th.halign-right,td.halign-right{text-align:right}
th.halign-center,td.halign-center{text-align:center}
th.valign-top,td.valign-top{vertical-align:top}
th.valign-bottom,td.valign-bottom{vertical-align:bottom}
th.valign-middle,td.valign-middle{vertical-align:middle}
table thead th,table tfoot th{font-weight:bold}
tbody tr th{background:#f7f8f7}
tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold}
p.tableblock>code:only-child{background:none;padding:0}
p.tableblock{font-size:1em}
ol{margin-left:1.75em}
ul li ol{margin-left:1.5em}
dl dd{margin-left:1.125em}
dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0}
ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em}
ul.checklist,ul.none,ol.none,ul.no-bullet,ol.no-bullet,ol.unnumbered,ul.unstyled,ol.unstyled{list-style-type:none}
ul.no-bullet,ol.no-bullet,ol.unnumbered{margin-left:.625em}
ul.unstyled,ol.unstyled{margin-left:0}
ul.checklist>li>p:first-child{margin-left:-1em}
ul.checklist>li>p:first-child>.fa-square-o:first-child,ul.checklist>li>p:first-child>.fa-check-square-o:first-child{width:1.25em;font-size:.8em;position:relative;bottom:.125em}
ul.checklist>li>p:first-child>input[type=checkbox]:first-child{margin-right:.25em}
ul.inline{display:flex;flex-flow:row wrap;list-style:none;margin:0 0 .625em -1.25em}
ul.inline>li{margin-left:1.25em}
.unstyled dl dt{font-weight:400;font-style:normal}
ol.arabic{list-style-type:decimal}
ol.decimal{list-style-type:decimal-leading-zero}
ol.loweralpha{list-style-type:lower-alpha}
ol.upperalpha{list-style-type:upper-alpha}
ol.lowerroman{list-style-type:lower-roman}
ol.upperroman{list-style-type:upper-roman}
ol.lowergreek{list-style-type:lower-greek}
.hdlist>table,.colist>table{border:0;background:none}
.hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none}
td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em}
td.hdlist1{font-weight:bold;padding-bottom:1.25em}
td.hdlist2{word-wrap:anywhere}
.literalblock+.colist,.listingblock+.colist{margin-top:-.5em}
.colist td:not([class]):first-child{padding:.4em .75em 0;line-height:1;vertical-align:top}
.colist td:not([class]):first-child img{max-width:none}
.colist td:not([class]):last-child{padding:.25em 0}
.thumb,.th{line-height:0;display:inline-block;border:4px solid #fff;box-shadow:0 0 0 1px #ddd}
.imageblock.left{margin:.25em .625em 1.25em 0}
.imageblock.right{margin:.25em 0 1.25em .625em}
.imageblock>.title{margin-bottom:0}
.imageblock.thumb,.imageblock.th{border-width:6px}
.imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em}
.image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0}
.image.left{margin-right:.625em}
.image.right{margin-left:.625em}
a.image{text-decoration:none;display:inline-block}
a.image object{pointer-events:none}
sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super}
sup.footnote a,sup.footnoteref a{text-decoration:none}
sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline}
#footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em}
#footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em;border-width:1px 0 0}
#footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;margin-bottom:.2em}
#footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none;margin-left:-1.05em}
#footnotes .footnote:last-of-type{margin-bottom:0}
#content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0}
.gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0}
.gist .file-data>table td.line-data{width:99%}
div.unbreakable{page-break-inside:avoid}
.big{font-size:larger}
.small{font-size:smaller}
.underline{text-decoration:underline}
.overline{text-decoration:overline}
.line-through{text-decoration:line-through}
.aqua{color:#00bfbf}
.aqua-background{background:#00fafa}
.black{color:#000}
.black-background{background:#000}
.blue{color:#0000bf}
.blue-background{background:#0000fa}
.fuchsia{color:#bf00bf}
.fuchsia-background{background:#fa00fa}
.gray{color:#606060}
.gray-background{background:#7d7d7d}
.green{color:#006000}
.green-background{background:#007d00}
.lime{color:#00bf00}
.lime-background{background:#00fa00}
.maroon{color:#600000}
.maroon-background{background:#7d0000}
.navy{color:#000060}
.navy-background{background:#00007d}
.olive{color:#606000}
.olive-background{background:#7d7d00}
.purple{color:#600060}
.purple-background{background:#7d007d}
.red{color:#bf0000}
.red-background{background:#fa0000}
.silver{color:#909090}
.silver-background{background:#bcbcbc}
.teal{color:#006060}
.teal-background{background:#007d7d}
.white{color:#bfbfbf}
.white-background{background:#fafafa}
.yellow{color:#bfbf00}
.yellow-background{background:#fafa00}
span.icon>.fa{cursor:default}
a span.icon>.fa{cursor:inherit}
.admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default}
.admonitionblock td.icon .icon-note::before{content:"\f05a";color:#19407c}
.admonitionblock td.icon .icon-tip::before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111}
.admonitionblock td.icon .icon-warning::before{content:"\f071";color:#bf6900}
.admonitionblock td.icon .icon-caution::before{content:"\f06d";color:#bf3400}
.admonitionblock td.icon .icon-important::before{content:"\f06a";color:#bf0000}
.conum[data-value]{display:inline-block;color:#fff!important;background:rgba(0,0,0,.8);border-radius:50%;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold}
.conum[data-value] *{color:#fff!important}
.conum[data-value]+b{display:none}
.conum[data-value]::after{content:attr(data-value)}
pre .conum[data-value]{position:relative;top:-.125em}
b.conum *{color:inherit!important}
.conum:not([data-value]):empty{display:none}
dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility}
h1,h2,p,td.content,span.alt,summary{letter-spacing:-.01em}
p strong,td.content strong,div.footnote strong{letter-spacing:-.005em}
p,blockquote,dt,td.content,span.alt,summary{font-size:1.0625rem}
p{margin-bottom:1.25rem}
.sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em}
.exampleblock>.content{background:#fffef7;border-color:#e0e0dc;box-shadow:0 1px 4px #e0e0dc}
.print-only{display:none!important}
@page{margin:1.25cm .75cm}
@media print{*{box-shadow:none!important;text-shadow:none!important}
html{font-size:80%}
a{color:inherit!important;text-decoration:underline!important}
a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important}
a[href^="http:"]:not(.bare)::after,a[href^="https:"]:not(.bare)::after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em}
abbr[title]{border-bottom:1px dotted}
abbr[title]::after{content:" (" attr(title) ")"}
pre,blockquote,tr,img,object,svg{page-break-inside:avoid}
thead{display:table-header-group}
svg{max-width:100%}
p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3}
h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid}
#header,#content,#footnotes,#footer{max-width:none}
#toc,.sidebarblock,.exampleblock>.content{background:none!important}
#toc{border-bottom:1px solid #dddddf!important;padding-bottom:0!important}
body.book #header{text-align:center}
body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em}
body.book #header .details{border:0!important;display:block;padding:0!important}
body.book #header .details span:first-child{margin-left:0!important}
body.book #header .details br{display:block}
body.book #header .details br+span::before{content:none!important}
body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important}
body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always}
.listingblock code[data-lang]::before{display:block}
#footer{padding:0 .9375em}
.hide-on-print{display:none!important}
.print-only{display:block!important}
.hide-for-print{display:none!important}
.show-for-print{display:inherit!important}}
@media amzn-kf8,print{#header>h1:first-child{margin-top:1.25rem}
.sect1{padding:0!important}
.sect1+.sect1{border:0}
#footer{background:none}
#footer-text{color:rgba(0,0,0,.6);font-size:.9em}}
@media amzn-kf8{#header,#content,#footnotes,#footer{padding:0}}
</style>
</head>
<body class="article toc2 toc-left">
<div id="header">
<h1>Simple C&#43;&#43;11 metaprogramming</h1>
<div class="details">
<span id="author" class="author">Peter Dimov</span><br>
<span id="revdate">2015-05-26</span>
</div>
<div id="toc" class="toc2">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#c11_changes_the_playing_field">C&#43;&#43;11 changes the playing field</a></li>
<li><a href="#type_lists_and_mp_rename">Type lists and mp_rename</a></li>
<li><a href="#mp_transform">mp_transform</a></li>
<li><a href="#mp_transform_part_two">mp_transform, part two</a></li>
<li><a href="#the_infamous_tuple_cat_challenge">The infamous tuple_cat challenge</a></li>
<li><a href="#higher_order_metaprogramming_or_lack_thereof">Higher order metaprogramming, or lack thereof</a></li>
<li><a href="#one_more_thing">One more thing</a></li>
<li><a href="#conclusion">Conclusion</a></li>
<li><a href="#further_reading">Further reading</a></li>
</ul>
</div>
</div>
<div id="content">
<div id="preamble">
<div class="sectionbody">
<div class="paragraph lead">
<p><em>With variadic templates, parameter packs and template aliases</em></p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
I was motivated to write this after I read Eric Niebler&#8217;s
thought-provoking
<a href="http://ericniebler.com/2014/11/13/tiny-metaprogramming-library/">Tiny
Metaprogramming Library</a> article. Thanks Eric.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="c11_changes_the_playing_field">C&#43;&#43;11 changes the playing field</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The wide acceptance of <a href="http://www.boost.org/libs/mpl">Boost.MPL</a> made C&#43;&#43;
metaprogramming seem a solved problem. Perhaps MPL wasn&#8217;t ideal, but it was
good enough to the point that there wasn&#8217;t really a need to seek or produce
alternatives.</p>
</div>
<div class="paragraph">
<p>C&#43;&#43;11 changed the playing field. The addition of variadic templates with
their associated parameter packs added a compile-time list of types structure
directly into the language. Whereas before every metaprogramming library
defined its own type list, and MPL defined several, in C&#43;&#43;11, type lists are
as easy as</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>// C++11
template&lt;class... T&gt; struct type_list {};</code></pre>
</div>
</div>
<div class="paragraph">
<p>and there is hardly a reason to use anything else.</p>
</div>
<div class="paragraph">
<p>Template aliases are another game changer. Previously, "metafunctions", that
is, templates that took one type and produced another, looked like</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>// C++03
template&lt;class T&gt; struct add_pointer { typedef T* type; };</code></pre>
</div>
</div>
<div class="paragraph">
<p>and were used in the following manner:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>// C++03
typedef typename add_pointer&lt;X&gt;::type Xp;</code></pre>
</div>
</div>
<div class="paragraph">
<p>In C&#43;&#43;11, metafunctions can be template aliases, instead of class templates:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>// C++11
template&lt;class T&gt; using add_pointer = T*;</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above example use then becomes</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>// C++11
typedef add_pointer&lt;X&gt; Xp;</code></pre>
</div>
</div>
<div class="paragraph">
<p>or, if you prefer to be seen as C&#43;&#43;11-savvy,</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>// C++11
using Xp = add_pointer&lt;X&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is a considerable improvement in more complex expressions:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>// C++03
typedef
    typename add_reference&lt;
        typename add_const&lt;
            typename add_pointer&lt;X&gt;::type
        &gt;::type
    &gt;::type Xpcr;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>// C++11
using Xpcr = add_reference&lt;add_const&lt;add_pointer&lt;X&gt;&gt;&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>(The example also takes advantage of another C&#43;&#43;11 feature - you can now use
<code>&gt;&gt;</code> to close templates without it being interpreted as a right shift.)</p>
</div>
<div class="paragraph">
<p>In addition, template aliases can be passed to template template parameters:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>// C++11
template&lt;template&lt;class... T&gt; class F&gt; struct X
{
};

X&lt;add_pointer&gt;; // works!</code></pre>
</div>
</div>
<div class="paragraph">
<p>These language improvements allow for C&#43;&#43;11 metaprogramming that is
substantially different than its idiomatic C&#43;&#43;03 equivalent. Boost.MPL is no
longer good enough, and <em>something must be done</em>. But what?</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="type_lists_and_mp_rename">Type lists and mp_rename</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Let&#8217;s start with the basics. Our basic data structure will be the type list:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class... T&gt; struct mp_list {};</code></pre>
</div>
</div>
<div class="paragraph">
<p>Why the <code>mp_</code> prefix? mp obviously stands for metaprogramming, but could we not
have used a namespace?</p>
</div>
<div class="paragraph">
<p>Indeed we could have. Past experience with Boost.MPL however indicates that
name conflicts between our metaprogramming primitives and standard identifiers
(such as <code>list</code>) and keywords (such as <code>if</code>, <code>int</code> or <code>true</code>) will be common
and will be a source of problems. With a prefix, we avoid all that trouble.</p>
</div>
<div class="paragraph">
<p>So we have our type list and can put things into it:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>using list = mp_list&lt;int, char, float, double, void&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>but can&#8217;t do anything else with it yet. We&#8217;ll need a library of primitives that
operate on <code>mp_list</code>s. But before we get into that, let&#8217;s consider another
interesting question first.</p>
</div>
<div class="paragraph">
<p>Suppose we have our library of primitives that can do things with a <code>mp_list</code>,
but some other code hands us a type list that is not an <code>mp_list</code>, such as for
example an <code>std::tuple&lt;int, float, void*&gt;</code>, or
<code><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4115.html">std::packer</a>&lt;int,
float, void*&gt;</code>.</p>
</div>
<div class="paragraph">
<p>Suppose we need to modify this external list of types in some manner (change
the types into pointers, perhaps) and give back the transformed result in the
form it was given to us, <code>std::tuple&lt;int*, float*, void**&gt;</code> in the first
case and <code>std::packer&lt;int*, float*, void**&gt;</code> in the second.</p>
</div>
<div class="paragraph">
<p>To do that, we need to first convert <code>std::tuple&lt;int, float, void*&gt;</code> to
<code>mp_list&lt;int, float, void*&gt;</code>, apply <code>add_pointer</code> to each element obtaining
<code>mp_list&lt;int*, float*, void**&gt;</code>, then convert that back to <code>std::tuple</code>.</p>
</div>
<div class="paragraph">
<p>These conversion steps are a quite common occurrence, and we&#8217;ll write a
primitive that helps us perform them, called <code>mp_rename</code>. We want</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>mp_rename&lt;std::tuple&lt;int, float, void*&gt;, mp_list&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>to give us</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>mp_list&lt;int, float, void*&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>and conversely,</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>mp_rename&lt;mp_list&lt;int, float, void*&gt;, std::tuple&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>to give us</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>std::tuple&lt;int, float, void*&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here is the implementation of <code>mp_rename</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class A, template&lt;class...&gt; class B&gt; struct mp_rename_impl;

template&lt;template&lt;class...&gt; class A, class... T, template&lt;class...&gt; class B&gt;
    struct mp_rename_impl&lt;A&lt;T...&gt;, B&gt;
{
    using type = B&lt;T...&gt;;
};

template&lt;class A, template&lt;class...&gt; class B&gt;
    using mp_rename = typename mp_rename_impl&lt;A, B&gt;::type;</code></pre>
</div>
</div>
<div class="paragraph">
<p>(This pattern of a template alias forwarding to a class template doing the
actual work is common; class templates can be specialized, whereas template
aliases cannot.)</p>
</div>
<div class="paragraph">
<p>Note that <code>mp_rename</code> does not treat any list type as special, not even
<code>mp_list</code>; it can rename any variadic class template into any other. You could
use it to rename <code>std::packer</code> to <code>std::tuple</code> to <code>std::variant</code> (once there is
such a thing) and it will happily oblige.</p>
</div>
<div class="paragraph">
<p>In fact, it can even rename non-variadic class templates, as in the following
examples:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>mp_rename&lt;std::pair&lt;int, float&gt;, std::tuple&gt;        // -&gt; std::tuple&lt;int, float&gt;
mp_rename&lt;mp_list&lt;int, float&gt;, std::pair&gt;           // -&gt; std::pair&lt;int, float&gt;
mp_rename&lt;std::shared_ptr&lt;int&gt;, std::unique_ptr&gt;    // -&gt; std::unique_ptr&lt;int&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>There is a limit to the magic; <code>unique_ptr</code> can&#8217;t be renamed to <code>shared_ptr</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>mp_rename&lt;std::unique_ptr&lt;int&gt;, std::shared_ptr&gt;    // error</code></pre>
</div>
</div>
<div class="paragraph">
<p>because <code>unique_ptr&lt;int&gt;</code> is actually <code>unique_ptr&lt;int,
std::default_delete&lt;int&gt;&gt;</code> and <code>mp_rename</code> renames it to <code>shared_ptr&lt;int,
std::default_delete&lt;int&gt;&gt;</code>, which doesn&#8217;t compile. But it still works in many
more cases than one would naively expect at first.</p>
</div>
<div class="paragraph">
<p>With conversions no longer a problem, let&#8217;s move on to primitives and define a
simple one, <code>mp_size</code>, for practice. We want <code>mp_size&lt;mp_list&lt;T...&gt;&gt;</code> to
give us the number of elements in the list, that is, the value of the
expression <code>sizeof...(T)</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class L&gt; struct mp_size_impl;

template&lt;class... T&gt; struct mp_size_impl&lt;mp_list&lt;T...&gt;&gt;
{
    using type = std::integral_constant&lt;std::size_t, sizeof...(T)&gt;;
};

template&lt;class L&gt; using mp_size = typename mp_size_impl&lt;L&gt;::type;</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is relatively straightforward, except for the <code>std::integral_constant</code>.
What is it and why do we need it?</p>
</div>
<div class="paragraph">
<p><code>std::integral_constant</code> is a standard C&#43;&#43;11 type that wraps an integral
constant (that is, a compile-time constant integer value) into a type.</p>
</div>
<div class="paragraph">
<p>Since metaprogramming operates on type lists, which can only hold types, it&#8217;s
convenient to represent compile-time constants as types. This allows us to
treat lists of types and lists of values in a uniform manner. It is therefore
idiomatic in metaprogramming to take and return types instead of values, and
this is what we have done. If at some later point we want the actual value, we
can use the expression <code>mp_size&lt;L&gt;::value</code> to retrieve it.</p>
</div>
<div class="paragraph">
<p>We now have our <code>mp_size</code>, but you may have noticed that there&#8217;s an interesting
difference between <code>mp_size</code> and <code>mp_rename</code>. Whereas I made a point of
<code>mp_rename</code> not treating <code>mp_list</code> as a special case, <code>mp_size</code> very much does:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class... T&gt; struct mp_size_impl&lt;mp_list&lt;T...&gt;&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Is this really necessary? Can we not use the same technique in the
implementation of <code>mp_size</code> as we did in <code>mp_rename</code>?</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class L&gt; struct mp_size_impl;

template&lt;template&lt;class...&gt; class L, class... T&gt; struct mp_size_impl&lt;L&lt;T...&gt;&gt;
{
    using type = std::integral_constant&lt;std::size_t, sizeof...(T)&gt;;
};

template&lt;class L&gt; using mp_size = typename mp_size_impl&lt;L&gt;::type;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Yes, we very much can, and this improvement allows us to use <code>mp_size</code> on any
other type lists, such as <code>std::tuple</code>. It turns <code>mp_size</code> into a truly generic
primitive.</p>
</div>
<div class="paragraph">
<p>This is nice. It is so nice that I&#8217;d argue that all our metaprogramming
primitives ought to have this property. If someone hands us a type list in the
form of an <code>std::tuple</code>, we should be able to operate on it directly, avoiding
the conversions to and from <code>mp_list</code>.</p>
</div>
<div class="paragraph">
<p>So do we no longer have any need for <code>mp_rename</code>? Not quite. Apart from the
fact that sometimes we really do need to rename type lists, there is another
surprising task for which <code>mp_rename</code> is useful.</p>
</div>
<div class="paragraph">
<p>To illustrate it, let me introduce the primitive <code>mp_length</code>. It&#8217;s similar to
<code>mp_size</code>, but while <code>mp_size</code> takes a type list as an argument, <code>mp_length</code>
takes a variadic parameter pack and returns its length; or, stated differently,
it returns its number of arguments:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class... T&gt; using mp_length =
    std::integral_constant&lt;std::size_t, sizeof...(T)&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>How would we implement <code>mp_size</code> in terms of <code>mp_length</code>? One option is to just
substitute the implementation of the latter into the former:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;template&lt;class...&gt; class L, class... T&gt; struct mp_size_impl&lt;L&lt;T...&gt;&gt;
{
    using type = mp_length&lt;T...&gt;;
};</code></pre>
</div>
</div>
<div class="paragraph">
<p>but there is another way, much less mundane. Think about what <code>mp_size</code> does.
It takes the argument</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code><strong>mp_list</strong>&lt;int, void, float&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>and returns</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code><strong>mp_length</strong>&lt;int, void, float&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Do we already have a primitive that does a similar thing?</p>
</div>
<div class="paragraph">
<p>(Not much of a choice, is there?)</p>
</div>
<div class="paragraph">
<p>Indeed we have, and it&#8217;s called <code>mp_rename</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class L&gt; using mp_size = mp_rename&lt;L, mp_length&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>I don&#8217;t know about you, but I find this technique fascinating. It exploits the
structural similarity between a list, <code>L&lt;T...&gt;</code>, and a metafunction "call",
<code>F&lt;T...&gt;</code>, and the fact that the language sees the things the same way and
allows us to pass the template alias <code>mp_length</code> to <code>mp_rename</code> as if it were
an ordinary class template such as <code>mp_list</code>.</p>
</div>
<div class="paragraph">
<p>(Other metaprogramming libraries provide a dedicated <code>apply</code> primitive for
this job. <code>apply&lt;F, L&gt;</code> calls the metafunction <code>F</code> with the contents of the
list <code>L</code>. We&#8217;ll add an alias <code>mp_apply&lt;F, L&gt;</code> that calls <code>mp_rename&lt;L, F&gt;</code> for
readability.)</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;template&lt;class...&gt; class F, class L&gt; using mp_apply = mp_rename&lt;L, F&gt;;</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="mp_transform">mp_transform</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Let&#8217;s revisit the example I gave earlier - someone hands us <code>std::tuple&lt;X, Y,
Z&gt;</code> and we need to compute <code>std::tuple&lt;X*, Y*, Z*&gt;</code>. We already have
<code>add_pointer</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class T&gt; using add_pointer = T*;</code></pre>
</div>
</div>
<div class="paragraph">
<p>so we just need to apply it to each element of the input tuple.</p>
</div>
<div class="paragraph">
<p>The algorithm that takes a function and a list and applies the function to each
element is called <code>transform</code> in Boost.MPL and the STL and <code>map</code> in functional
languages. We&#8217;ll use <code>transform</code>, for consistency with the established C&#43;&#43;
practice (<code>map</code> is a data structure in both the STL and Boost.MPL.)</p>
</div>
<div class="paragraph">
<p>We&#8217;ll call our algorithm <code>mp_transform</code>, and <code>mp_transform&lt;F, L&gt;</code> will apply
<code>F</code> to each element of <code>L</code> and return the result. Usually, the argument order
is reversed and the function comes last. Our reasons to put it at the front
will become evident later.</p>
</div>
<div class="paragraph">
<p>There are many ways to implement <code>mp_transform</code>; the one we&#8217;ll pick will make
use of another primitive, <code>mp_push_front</code>. <code>mp_push_front&lt;L, T&gt;</code>, as its name
implies, adds <code>T</code> as a first element in <code>L</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class L, class T&gt; struct mp_push_front_impl;

template&lt;template&lt;class...&gt; class L, class... U, class T&gt;
    struct mp_push_front_impl&lt;L&lt;U...&gt;, T&gt;
{
    using type = L&lt;T, U...&gt;;
};

template&lt;class L, class T&gt;
    using mp_push_front = typename mp_push_front_impl&lt;L, T&gt;::type;</code></pre>
</div>
</div>
<div class="paragraph">
<p>There is no reason to constrain <code>mp_push_front</code> to a single element though. In
C&#43;&#43;11, variadic templates should be our default choice, and the
implementation of <code>mp_push_front</code> that can take an arbitrary number of elements
is almost identical:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class L, class... T&gt; struct mp_push_front_impl;

template&lt;template&lt;class...&gt; class L, class... U, class... T&gt;
    struct mp_push_front_impl&lt;L&lt;U...&gt;, T...&gt;
{
    using type = L&lt;T..., U...&gt;;
};

template&lt;class L, class... T&gt;
    using mp_push_front = typename mp_push_front_impl&lt;L, T...&gt;::type;</code></pre>
</div>
</div>
<div class="paragraph">
<p>On to <code>mp_transform</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;template&lt;class...&gt; class F, class L&gt; struct mp_transform_impl;

template&lt;template&lt;class...&gt; class F, class L&gt;
    using mp_transform = typename mp_transform_impl&lt;F, L&gt;::type;

template&lt;template&lt;class...&gt; class F, template&lt;class...&gt; class L&gt;
    struct mp_transform_impl&lt;F, L&lt;&gt;&gt;
{
    using type = L&lt;&gt;;
};

template&lt;template&lt;class...&gt; class F, template&lt;class...&gt; class L, class T1, class... T&gt;
    struct mp_transform_impl&lt;F, L&lt;T1, T...&gt;&gt;
{
    using _first = F&lt;T1&gt;;
    using _rest = mp_transform&lt;F, L&lt;T...&gt;&gt;;

    using type = mp_push_front&lt;_rest, _first&gt;;
};</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is a straightforward recursive implementation that should be familiar to
people with functional programming background.</p>
</div>
<div class="paragraph">
<p>Can we do better? It turns out that in C&#43;&#43;11, we can.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;template&lt;class...&gt; class F, class L&gt; struct mp_transform_impl;

template&lt;template&lt;class...&gt; class F, class L&gt;
    using mp_transform = typename mp_transform_impl&lt;F, L&gt;::type;

template&lt;template&lt;class...&gt; class F, template&lt;class...&gt; class L, class... T&gt;
    struct mp_transform_impl&lt;F, L&lt;T...&gt;&gt;
{
    using type = L&lt;F&lt;T&gt;...&gt;;
};</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here we take advantage of the fact that pack expansion is built into the
language, so the <code>F&lt;T&gt;...</code> part does all the iteration work for us.</p>
</div>
<div class="paragraph">
<p>We can now solve our original challenge: given an <code>std::tuple</code> of types, return
an <code>std::tuple</code> of pointers to these types:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>using input = std::tuple&lt;int, void, float&gt;;
using expected = std::tuple&lt;int*, void*, float*&gt;;

using result = mp_transform&lt;add_pointer, input&gt;;

static_assert( std::is_same&lt;result, expected&gt;::value, "" );</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="mp_transform_part_two">mp_transform, part two</h2>
<div class="sectionbody">
<div class="paragraph">
<p>What if we had a pair of tuples as input, and had to produce the corresponding
tuple of pairs? For example, given</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>using input = std::pair&lt;std::tuple&lt;X1, X2, X3&gt;, std::tuple&lt;Y1, Y2, Y3&gt;&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>we had to produce</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>using expected = std::tuple&lt;std::pair&lt;X1, Y1&gt;, std::pair&lt;X2, Y2&gt;, std::pair&lt;X3, Y3&gt;&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>We need to take the two lists, represented by tuples in the input, and combine
them pairwise by using <code>std::pair</code>. If we think of <code>std::pair</code> as a function
<code>F</code>, this task appears very similar to <code>mp_transform</code>, except we need to use a
binary function and two lists.</p>
</div>
<div class="paragraph">
<p>Changing our unary transform algorithm into a binary one isn&#8217;t hard:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;template&lt;class...&gt; class F, class L1, class L2&gt;
    struct mp_transform2_impl;

template&lt;template&lt;class...&gt; class F, class L1, class L2&gt;
    using mp_transform2 = typename mp_transform2_impl&lt;F, L1, L2&gt;::type;

template&lt;template&lt;class...&gt; class F,
    template&lt;class...&gt; class L1, class... T1,
    template&lt;class...&gt; class L2, class... T2&gt;
    struct mp_transform2_impl&lt;F, L1&lt;T1...&gt;, L2&lt;T2...&gt;&gt;
{
    static_assert( sizeof...(T1) == sizeof...(T2),
        "The arguments of mp_transform2 should be of the same size" );

    using type = L1&lt;F&lt;T1,T2&gt;...&gt;;
};</code></pre>
</div>
</div>
<div class="paragraph">
<p>and we can now do</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>using input = std::pair&lt;std::tuple&lt;X1, X2, X3&gt;, std::tuple&lt;Y1, Y2, Y3&gt;&gt;;
using expected = std::tuple&lt;std::pair&lt;X1, Y1&gt;, std::pair&lt;X2, Y2&gt;, std::pair&lt;X3, Y3&gt;&gt;;

using result = mp_transform2&lt;std::pair, input::first_type, input::second_type&gt;;

static_assert( std::is_same&lt;result, expected&gt;::value, "" );</code></pre>
</div>
</div>
<div class="paragraph">
<p>again exploiting the similarity between metafunctions and ordinary class
templates such as <code>std::pair</code>, this time in the other direction; we pass
<code>std::pair</code> where <code>mp_transform2</code> expects a metafunction.</p>
</div>
<div class="paragraph">
<p>Do we <em>have</em> to use separate transform algorithms for each arity though? If we
need a transform algorithm that takes a ternary function and three lists,
should we name it <code>mp_transform3</code>? No, this is exactly why we put the function
first. We just have to change <code>mp_transform</code> to be variadic:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;template&lt;class...&gt; class F, class... L&gt; struct mp_transform_impl;

template&lt;template&lt;class...&gt; class F, class... L&gt;
    using mp_transform = typename mp_transform_impl&lt;F, L...&gt;::type;</code></pre>
</div>
</div>
<div class="paragraph">
<p>and then add the unary and binary specializations:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;template&lt;class...&gt; class F, template&lt;class...&gt; class L, class... T&gt;
    struct mp_transform_impl&lt;F, L&lt;T...&gt;&gt;
{
    using type = L&lt;F&lt;T&gt;...&gt;;
};

template&lt;template&lt;class...&gt; class F,
    template&lt;class...&gt; class L1, class... T1,
    template&lt;class...&gt; class L2, class... T2&gt;
    struct mp_transform_impl&lt;F, L1&lt;T1...&gt;, L2&lt;T2...&gt;&gt;
{
    static_assert( sizeof...(T1) == sizeof...(T2),
        "The arguments of mp_transform should be of the same size" );

    using type = L1&lt;F&lt;T1,T2&gt;...&gt;;
};</code></pre>
</div>
</div>
<div class="paragraph">
<p>We can also add ternary and further specializations.</p>
</div>
<div class="paragraph">
<p>Is it possible to implement the truly variadic <code>mp_transform</code>, one that works
with an arbitrary number of lists? It is in principle, and I&#8217;ll show one
possible abridged implementation here for completeness:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;template&lt;class...&gt; class F, class E, class... L&gt;
    struct mp_transform_impl;

template&lt;template&lt;class...&gt; class F, class... L&gt;
    using mp_transform = typename mp_transform_impl&lt;F, mp_empty&lt;L...&gt;, L...&gt;::type;

template&lt;template&lt;class...&gt; class F, class L1, class... L&gt;
    struct mp_transform_impl&lt;F, mp_true, L1, L...&gt;
{
    using type = mp_clear&lt;L1&gt;;
};

template&lt;template&lt;class...&gt; class F, class... L&gt;
    struct mp_transform_impl&lt;F, mp_false, L...&gt;
{
    using _first = F&lt; typename mp_front_impl&lt;L&gt;::type... &gt;;
    using _rest = mp_transform&lt; F, typename mp_pop_front_impl&lt;L&gt;::type... &gt;;

    using type = mp_push_front&lt;_rest, _first&gt;;
};</code></pre>
</div>
</div>
<div class="paragraph">
<p>but will omit the primitives that it uses. These are</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>mp_true</code>&#8201;&#8212;&#8201;an alias for <code>std::integral_constant&lt;bool, true&gt;</code>.</p>
</li>
<li>
<p><code>mp_false</code>&#8201;&#8212;&#8201;an alias for <code>std::integral_constant&lt;bool, false&gt;</code>.</p>
</li>
<li>
<p><code>mp_empty&lt;L...&gt;</code>&#8201;&#8212;&#8201;returns <code>mp_true</code> if all lists are empty, <code>mp_false</code>
otherwise.</p>
</li>
<li>
<p><code>mp_clear&lt;L&gt;</code>&#8201;&#8212;&#8201;returns an empty list of the same type as <code>L</code>.</p>
</li>
<li>
<p><code>mp_front&lt;L&gt;</code>&#8201;&#8212;&#8201;returns the first element of <code>L</code>.</p>
</li>
<li>
<p><code>mp_pop_front&lt;L&gt;</code>&#8201;&#8212;&#8201;returns <code>L</code> without its first element.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>There is one interesting difference between the recursive <code>mp_transform</code>
implementation and the language-based one. <code>mp_transform&lt;add_pointer,
std::pair&lt;int, float&gt;&gt;</code> works with the <code>F&lt;T&gt;...</code> implementation and fails
with the recursive one, because <code>std::pair</code> is not a real type list and can
only hold exactly two types.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="the_infamous_tuple_cat_challenge">The infamous tuple_cat challenge</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Eric Niebler, in his
<a href="http://ericniebler.com/2014/11/13/tiny-metaprogramming-library/">Tiny
Metaprogramming Library</a> article, gives the function
<a href="http://en.cppreference.com/w/cpp/utility/tuple/tuple_cat"><code>std::tuple_cat</code></a> as a
kind of a metaprogramming challenge. <code>tuple_cat</code> is a variadic template
function that takes a number of tuples and concatenates them into another
<code>std::tuple</code>. This is Eric&#8217;s solution:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>namespace detail
{
    template&lt;typename Ret, typename...Is, typename ...Ks,
        typename Tuples&gt;
    Ret tuple_cat_(typelist&lt;Is...&gt;, typelist&lt;Ks...&gt;,
        Tuples tpls)
    {
        return Ret{std::get&lt;Ks::value&gt;(
            std::get&lt;Is::value&gt;(tpls))...};
    }
}

template&lt;typename...Tuples,
    typename Res =
        typelist_apply_t&lt;
            meta_quote&lt;std::tuple&gt;,
            typelist_cat_t&lt;typelist&lt;as_typelist_t&lt;Tuples&gt;...&gt; &gt; &gt; &gt;
Res tuple_cat(Tuples &amp;&amp;... tpls)
{
    static constexpr std::size_t N = sizeof...(Tuples);
    // E.g. [0,0,0,2,2,2,3,3]
    using inner =
        typelist_cat_t&lt;
            typelist_transform_t&lt;
                typelist&lt;as_typelist_t&lt;Tuples&gt;...&gt;,
                typelist_transform_t&lt;
                    as_typelist_t&lt;make_index_sequence&lt;N&gt; &gt;,
                    meta_quote&lt;meta_always&gt; &gt;,
                meta_quote&lt;typelist_transform_t&gt; &gt; &gt;;
    // E.g. [0,1,2,0,1,2,0,1]
    using outer =
        typelist_cat_t&lt;
            typelist_transform_t&lt;
                typelist&lt;as_typelist_t&lt;Tuples&gt;...&gt;,
                meta_compose&lt;
                    meta_quote&lt;as_typelist_t&gt;,
                    meta_quote_i&lt;std::size_t, make_index_sequence&gt;,
                    meta_quote&lt;typelist_size_t&gt; &gt; &gt; &gt;;
    return detail::tuple_cat_&lt;Res&gt;(
        inner{},
        outer{},
        std::forward_as_tuple(std::forward&lt;Tuples&gt;(tpls)...));
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>All right, challenge accepted. Let&#8217;s see what we can do.</p>
</div>
<div class="paragraph">
<p>As Eric explains, this implementation relies on the clever trick of packing the
input tuples into a tuple, creating two arrays of indices, <code>inner</code> and <code>outer</code>,
then indexing the outer tuple with the outer indices and the result, which is
one of our input tuples, with the inner indices.</p>
</div>
<div class="paragraph">
<p>So, for example, if tuple_cat is invoked as</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>std::tuple&lt;int, short, long&gt; t1;
std::tuple&lt;&gt; t2;
std::tuple&lt;float, double, long double&gt; t3;
std::tuple&lt;void*, char*&gt; t4;

auto res = tuple_cat(t1, t2, t3, t4);</code></pre>
</div>
</div>
<div class="paragraph">
<p>we&#8217;ll create the tuple</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>std::tuple&lt;std::tuple&lt;int, short, long&gt;, std::tuple&lt;&gt;,
    std::tuple&lt;float, double, long double&gt;, std::tuple&lt;void*, char*&gt;&gt; t{t1, t2, t3, t4};</code></pre>
</div>
</div>
<div class="paragraph">
<p>and then extract the elements of t via</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>std::get&lt;0&gt;(std::get&lt;0&gt;(t)), // t1[0]
std::get&lt;1&gt;(std::get&lt;0&gt;(t)), // t1[1]
std::get&lt;2&gt;(std::get&lt;0&gt;(t)), // t1[2]
std::get&lt;0&gt;(std::get&lt;2&gt;(t)), // t3[0]
std::get&lt;1&gt;(std::get&lt;2&gt;(t)), // t3[1]
std::get&lt;2&gt;(std::get&lt;2&gt;(t)), // t3[2]
std::get&lt;0&gt;(std::get&lt;3&gt;(t)), // t4[0]
std::get&lt;1&gt;(std::get&lt;3&gt;(t)), // t4[1]</code></pre>
</div>
</div>
<div class="paragraph">
<p>(<code>t2</code> is empty, so we take nothing from it.)</p>
</div>
<div class="paragraph">
<p>The first column of integers is the <code>outer</code> array, the second one - the <code>inner</code>
array, and these are what we need to compute. But first, let&#8217;s deal with the
return type of <code>tuple_cat</code>.</p>
</div>
<div class="paragraph">
<p>The return type of <code>tuple_cat</code> is just the concatenation of the arguments,
viewed as type lists. The metaprogramming algorithm that concatenates lists is
called
<a href="https://ericniebler.github.io/meta/group__transformation.html"><code>meta::concat</code></a>
in Eric Niebler&#8217;s <a href="https://github.com/ericniebler/meta">Meta</a> library, but I&#8217;ll
call it <code>mp_append</code>, after its classic Lisp name.</p>
</div>
<div class="paragraph">
<p>(Lisp is today&#8217;s equivalent of Latin. Educated people are supposed to have
studied and forgotten it.)</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class... L&gt; struct mp_append_impl;

template&lt;class... L&gt; using mp_append = typename mp_append_impl&lt;L...&gt;::type;

template&lt;&gt; struct mp_append_impl&lt;&gt;
{
    using type = mp_list&lt;&gt;;
};

template&lt;template&lt;class...&gt; class L, class... T&gt; struct mp_append_impl&lt;L&lt;T...&gt;&gt;
{
    using type = L&lt;T...&gt;;
};

template&lt;template&lt;class...&gt; class L1, class... T1,
    template&lt;class...&gt; class L2, class... T2, class... Lr&gt;
    struct mp_append_impl&lt;L1&lt;T1...&gt;, L2&lt;T2...&gt;, Lr...&gt;
{
    using type = mp_append&lt;L1&lt;T1..., T2...&gt;, Lr...&gt;;
};</code></pre>
</div>
</div>
<div class="paragraph">
<p>That was fairly easy. There are other ways to implement <code>mp_append</code>, but this
one demonstrates how the language does most of the work for us via pack
expansion. This is a common theme in C&#43;&#43;11.</p>
</div>
<div class="paragraph">
<p>Note how <code>mp_append</code> returns the same list type as its first argument. Of
course, in the case in which no arguments are given, there is no first argument
from which to take the type, so I&#8217;ve arbitrarily chosen to return an empty
<code>mp_list</code>.</p>
</div>
<div class="paragraph">
<p>We&#8217;re now ready with the declaration of <code>tuple_cat</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class... Tp,
    class R = mp_append&lt;typename std::remove_reference&lt;Tp&gt;::type...&gt;&gt;
    R tuple_cat( Tp &amp;&amp;... tp );</code></pre>
</div>
</div>
<div class="paragraph">
<p>The reason we need <code>remove_reference</code> is because of the rvalue reference
parameters, used to implement perfect forwarding. If the argument is an lvalue,
such as for example <code>t1</code> above, its corresponding type will be a reference to a
tuple&#8201;&#8212;&#8201;<code>std::tuple&lt;int, short, long&gt;&amp;</code> in <code>t1</code>'s case. Our primitives do
not recognize references to tuples as type lists, so we need to strip them off.</p>
</div>
<div class="paragraph">
<p>There are two problems with our return type computation though. One, what if
<code>tuple_cat</code> is called without any arguments? We return <code>mp_list&lt;&gt;</code> in that
case, but the correct result is <code>std::tuple&lt;&gt;</code>.</p>
</div>
<div class="paragraph">
<p>Two, what if we call <code>tuple_cat</code> with a first argument that is a <code>std::pair</code>?
We&#8217;ll try to append more elements to <code>std::pair</code>, and it will fail.</p>
</div>
<div class="paragraph">
<p>We can solve both our problems by using an empty tuple as the first argument to
<code>mp_append</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class... Tp,
    class R = mp_append&lt;std::tuple&lt;&gt;, typename std::remove_reference&lt;Tp&gt;::type...&gt;&gt;
    R tuple_cat( Tp &amp;&amp;... tp );</code></pre>
</div>
</div>
<div class="paragraph">
<p>With the return type taken care of, let&#8217;s now move on to computing inner. We
have</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>[x1, x2, x3], [], [y1, y2, y3], [z1, z2]</code></pre>
</div>
</div>
<div class="paragraph">
<p>as input and we need to output</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>[0, 0, 0, 2, 2, 2, 3, 3]</code></pre>
</div>
</div>
<div class="paragraph">
<p>which is the concatenation of</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>[0, 0, 0], [], [2, 2, 2], [3, 3]</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here each tuple is the same size as the input, but is filled with a constant
that represents its index in the argument list. The first tuple is filled with
0, the second with 1, the third with 2, and so on.</p>
</div>
<div class="paragraph">
<p>We can achieve this result if we first compute a list of indices, in our case
<code>[0, 1, 2, 3]</code>, then use binary <code>mp_transform</code> on the two lists</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>[[x1, x2, x3], [], [y1, y2, y3], [z1, z2]]
[0, 1, 2, 3]</code></pre>
</div>
</div>
<div class="paragraph">
<p>and a function which takes a list and an integer (in the form of an
<code>std::integral_constant</code>) and returns a list that is the same size as the
original, but filled with the second argument.</p>
</div>
<div class="paragraph">
<p>We&#8217;ll call this function <code>mp_fill</code>, after <code>std::fill</code>.</p>
</div>
<div class="paragraph">
<p>Functional programmers will immediately realize that <code>mp_fill</code> is
<code>mp_transform</code> with a function that returns a constant, and here&#8217;s an
implementation along these lines:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class V&gt; struct mp_constant
{
    template&lt;class...&gt; using apply = V;
};

template&lt;class L, class V&gt;
    using mp_fill = mp_transform&lt;mp_constant&lt;V&gt;::template apply, L&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here&#8217;s an alternate implementation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class L, class V&gt; struct mp_fill_impl;

template&lt;template&lt;class...&gt; class L, class... T, class V&gt;
    struct mp_fill_impl&lt;L&lt;T...&gt;, V&gt;
{
    template&lt;class...&gt; using _fv = V;
    using type = L&lt;_fv&lt;T&gt;...&gt;;
};

template&lt;class L, class V&gt; using mp_fill = typename mp_fill_impl&lt;L, V&gt;::type;</code></pre>
</div>
</div>
<div class="paragraph">
<p>These demonstrate different styles and choosing one over the other is largely a
matter of taste here. In the first case, we combine existing primitives; in the
second case, we "inline" <code>mp_const</code> and even <code>mp_transform</code> in the body of
<code>mp_fill_impl</code>.</p>
</div>
<div class="paragraph">
<p>Most C&#43;&#43;11 programmers will probably find the second implementation easier to
read.</p>
</div>
<div class="paragraph">
<p>We can now <code>mp_fill</code>, but we still need the <code>[0, 1, 2, 3]</code> index sequence. We
could write an algorithm <code>mp_iota</code> for that (named after
<a href="http://en.cppreference.com/w/cpp/algorithm/iota"><code>std::iota</code></a>), but it so
happens that C&#43;&#43;14 already has a standard way of generating an index
sequence, called
<a href="http://en.cppreference.com/w/cpp/utility/integer_sequence"><code>std::make_index_sequence</code></a>.
Since Eric&#8217;s original solution makes use of <code>make_index_sequence</code>, let&#8217;s follow
his lead.</p>
</div>
<div class="paragraph">
<p>Technically, this takes us outside of C&#43;&#43;11, but <code>make_index_sequence</code> is not
hard to implement (if efficiency is not a concern):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class T, T... Ints&gt; struct integer_sequence
{
};

template&lt;class S&gt; struct next_integer_sequence;

template&lt;class T, T... Ints&gt; struct next_integer_sequence&lt;integer_sequence&lt;T, Ints...&gt;&gt;
{
    using type = integer_sequence&lt;T, Ints..., sizeof...(Ints)&gt;;
};

template&lt;class T, T I, T N&gt; struct make_int_seq_impl;

template&lt;class T, T N&gt;
    using make_integer_sequence = typename make_int_seq_impl&lt;T, 0, N&gt;::type;

template&lt;class T, T I, T N&gt; struct make_int_seq_impl
{
    using type = typename next_integer_sequence&lt;
        typename make_int_seq_impl&lt;T, I+1, N&gt;::type&gt;::type;
};

template&lt;class T, T N&gt; struct make_int_seq_impl&lt;T, N, N&gt;
{
    using type = integer_sequence&lt;T&gt;;
};

template&lt;std::size_t... Ints&gt;
    using index_sequence = integer_sequence&lt;std::size_t, Ints...&gt;;

template&lt;std::size_t N&gt;
    using make_index_sequence = make_integer_sequence&lt;std::size_t, N&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>We can now obtain an <code>index_sequence&lt;0, 1, 2, 3&gt;</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class... Tp,
    class R = mp_append&lt;std::tuple&lt;&gt;, typename std::remove_reference&lt;Tp&gt;::type...&gt;&gt;
    R tuple_cat( Tp &amp;&amp;... tp )
{
    std::size_t const N = sizeof...(Tp);

    // inner

    using seq = make_index_sequence&lt;N&gt;;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>but <code>make_index_sequence&lt;4&gt;</code> returns <code>integer_sequence&lt;std::size_t, 0, 1, 2,
3&gt;</code>, which is not a type list. In order to work with it, we need to convert it
to a type list, so we&#8217;ll introduce a function <code>mp_from_sequence</code> that does
that.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class S&gt; struct mp_from_sequence_impl;

template&lt;template&lt;class T, T... I&gt; class S, class U, U... J&gt;
    struct mp_from_sequence_impl&lt;S&lt;U, J...&gt;&gt;
{
    using type = mp_list&lt;std::integral_constant&lt;U, J&gt;...&gt;;
};

template&lt;class S&gt; using mp_from_sequence = typename mp_from_sequence_impl&lt;S&gt;::type;</code></pre>
</div>
</div>
<div class="paragraph">
<p>We can now compute the two lists that we wanted to transform with <code>mp_fill</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class... Tp,
    class R = mp_append&lt;std::tuple&lt;&gt;, typename std::remove_reference&lt;Tp&gt;::type...&gt;&gt;
    R tuple_cat( Tp &amp;&amp;... tp )
{
    std::size_t const N = sizeof...(Tp);

    // inner

    using list1 = mp_list&lt;typename std::remove_reference&lt;Tp&gt;::type...&gt;;
    using list2 = mp_from_sequence&lt;make_index_sequence&lt;N&gt;&gt;;

    // list1: [[x1, x2, x3], [], [y1, y2, y3], [z1, z2]]
    // list2: [0, 1, 2, 3]

    return R{};
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>and finish the job of computing <code>inner</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class... Tp,
    class R = mp_append&lt;std::tuple&lt;&gt;, typename std::remove_reference&lt;Tp&gt;::type...&gt;&gt;
    R tuple_cat( Tp &amp;&amp;... tp )
{
    std::size_t const N = sizeof...(Tp);

    // inner

    using list1 = mp_list&lt;typename std::remove_reference&lt;Tp&gt;::type...&gt;;
    using list2 = mp_from_sequence&lt;make_index_sequence&lt;N&gt;&gt;;

    // list1: [[x1, x2, x3], [], [y1, y2, y3], [z1, z2]]
    // list2: [0, 1, 2, 3]

    using list3 = mp_transform&lt;mp_fill, list1, list2&gt;;

    // list3: [[0, 0, 0], [], [2, 2, 2], [3, 3]]

    using inner = mp_rename&lt;list3, mp_append&gt;; // or mp_apply&lt;mp_append, list3&gt;

    // inner: [0, 0, 0, 2, 2, 2, 3, 3]

    return R{};
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>For <code>outer</code>, we again have</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>[x1, x2, x3], [], [y1, y2, y3], [z1, z2]</code></pre>
</div>
</div>
<div class="paragraph">
<p>as input and we need to output</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>[0, 1, 2, 0, 1, 2, 0, 1]</code></pre>
</div>
</div>
<div class="paragraph">
<p>which is the concatenation of</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>[0, 1, 2], [], [0, 1, 2], [0, 1]</code></pre>
</div>
</div>
<div class="paragraph">
<p>The difference here is that instead of filling the tuple with a constant value,
we need to fill it with increasing values, starting from 0, that is, with the
result of <code>make_index_sequence&lt;N&gt;</code>, where <code>N</code> is the number of elements.</p>
</div>
<div class="paragraph">
<p>The straightforward way to do that is to just define a metafunction <code>F</code> that
does what we want, then use <code>mp_transform</code> to apply it to the input:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class N&gt; using mp_iota = mp_from_sequence&lt;make_index_sequence&lt;N::value&gt;&gt;;

template&lt;class L&gt; using F = mp_iota&lt;mp_size&lt;L&gt;&gt;;

template&lt;class... Tp,
    class R = mp_append&lt;std::tuple&lt;&gt;, typename std::remove_reference&lt;Tp&gt;::type...&gt;&gt;
    R tuple_cat( Tp &amp;&amp;... tp )
{
    std::size_t const N = sizeof...(Tp);

    // outer

    using list1 = mp_list&lt;typename std::remove_reference&lt;Tp&gt;::type...&gt;;
    using list2 = mp_transform&lt;F, list1&gt;;

    // list2: [[0, 1, 2], [], [0, 1, 2], [0, 1]]

    using outer = mp_rename&lt;list2, mp_append&gt;;

    // outer: [0, 1, 2, 0, 1, 2, 0, 1]

    return R{};
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Well that was easy. Surprisingly easy. The one small annoyance is that we can&#8217;t
define <code>F</code> inside <code>tuple_cat</code> - templates can&#8217;t be defined in functions.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s put everything together.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class N&gt; using mp_iota = mp_from_sequence&lt;make_index_sequence&lt;N::value&gt;&gt;;

template&lt;class L&gt; using F = mp_iota&lt;mp_size&lt;L&gt;&gt;;

template&lt;class R, class...Is, class... Ks, class Tp&gt;
R tuple_cat_( mp_list&lt;Is...&gt;, mp_list&lt;Ks...&gt;, Tp tp )
{
    return R{ std::get&lt;Ks::value&gt;(std::get&lt;Is::value&gt;(tp))... };
}

template&lt;class... Tp,
    class R = mp_append&lt;std::tuple&lt;&gt;, typename std::remove_reference&lt;Tp&gt;::type...&gt;&gt;
    R tuple_cat( Tp &amp;&amp;... tp )
{
    std::size_t const N = sizeof...(Tp);

    // inner

    using list1 = mp_list&lt;typename std::remove_reference&lt;Tp&gt;::type...&gt;;
    using list2 = mp_from_sequence&lt;make_index_sequence&lt;N&gt;&gt;;

    // list1: [[x1, x2, x3], [], [y1, y2, y3], [z1, z2]]
    // list2: [0, 1, 2, 3]

    using list3 = mp_transform&lt;mp_fill, list1, list2&gt;;

    // list3: [[0, 0, 0], [], [2, 2, 2], [3, 3]]

    using inner = mp_rename&lt;list3, mp_append&gt;; // or mp_apply&lt;mp_append, list3&gt;

    // inner: [0, 0, 0, 2, 2, 2, 3, 3]

    // outer

    using list4 = mp_transform&lt;F, list1&gt;;

    // list4: [[0, 1, 2], [], [0, 1, 2], [0, 1]]

    using outer = mp_rename&lt;list4, mp_append&gt;;

    // outer: [0, 1, 2, 0, 1, 2, 0, 1]

    return tuple_cat_&lt;R&gt;( inner(), outer(),
        std::forward_as_tuple( std::forward&lt;Tp&gt;(tp)... ) );
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This almost compiles, except that our <code>inner</code> happens to be a <code>std::tuple</code>, but
our helper function expects an <code>mp_list</code>. (<code>outer</code> is already an <code>mp_list</code>, by
sheer luck.) We can fix that easily enough.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>return tuple_cat_&lt;R&gt;( mp_rename&lt;inner, mp_list&gt;(), outer(),
    std::forward_as_tuple( std::forward&lt;Tp&gt;(tp)... ) );</code></pre>
</div>
</div>
<div class="paragraph">
<p>Let&#8217;s define a <code>print_tuple</code> function and see if everything checks out.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;int I, int N, class... T&gt; struct print_tuple_
{
    void operator()( std::tuple&lt;T...&gt; const &amp; tp ) const
    {
        using Tp = typename std::tuple_element&lt;I, std::tuple&lt;T...&gt;&gt;::type;

        print_type&lt;Tp&gt;( " ", ": " );

        std::cout &lt;&lt; std::get&lt;I&gt;( tp ) &lt;&lt; ";";

        print_tuple_&lt; I+1, N, T... &gt;()( tp );
    }
};

template&lt;int N, class... T&gt; struct print_tuple_&lt;N, N, T...&gt;
{
    void operator()( std::tuple&lt;T...&gt; const &amp; ) const
    {
    }
};

template&lt;class... T&gt; void print_tuple( std::tuple&lt;T...&gt; const &amp; tp )
{
    std::cout &lt;&lt; "{";
    print_tuple_&lt;0, sizeof...(T), T...&gt;()( tp );
    std::cout &lt;&lt; " }\n";
}

int main()
{
    std::tuple&lt;int, long&gt; t1{ 1, 2 };
    std::tuple&lt;&gt; t2;
    std::tuple&lt;float, double, long double&gt; t3{ 3, 4, 5 };
    std::pair&lt;void const*, char const*&gt; t4{ "pv", "test" };

    using expected = std::tuple&lt;int, long, float, double, long double,
        void const*, char const*&gt;;

    auto result = ::tuple_cat( t1, t2, t3, t4 );

    static_assert( std::is_same&lt;decltype(result), expected&gt;::value, "" );

    print_tuple( result );
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Output:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>{ int: 1; long: 2; float: 3; double: 4; long double: 5; void const*: 0x407086;
    char const*: test; }</code></pre>
</div>
</div>
<div class="paragraph">
<p>Seems to work. But there&#8217;s at least one error left. To see why, replace the
first tuple</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>std::tuple&lt;int, long&gt; t1{ 1, 2 };</code></pre>
</div>
</div>
<div class="paragraph">
<p>with a pair:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>std::pair&lt;int, long&gt; t1{ 1, 2 };</code></pre>
</div>
</div>
<div class="paragraph">
<p>We now get an error at</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>using inner = mp_rename&lt;list3, mp_append&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>because the first element of <code>list3</code> is an <code>std::pair</code>, which <code>mp_append</code> tries
and fails to use as its return type.</p>
</div>
<div class="paragraph">
<p>There are two ways to fix that. The first one is to apply the same trick we
used for the return type, and insert an empty <code>mp_list</code> at the front of
<code>list3</code>, which <code>mp_append</code> will use as a return type:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>using inner = mp_rename&lt;mp_push_front&lt;list3, mp_list&lt;&gt;&gt;, mp_append&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>The second way is to just convert all inputs to mp_list:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>using list1 = mp_list&lt;
    mp_rename&lt;typename std::remove_reference&lt;Tp&gt;::type, mp_list&gt;...&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>In both cases, inner will now be an <code>mp_list</code>, so we can omit the <code>mp_rename</code>
in the call to <code>tuple_cat_</code>.</p>
</div>
<div class="paragraph">
<p>We&#8217;re done. The results hopefully speak for themselves.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="higher_order_metaprogramming_or_lack_thereof">Higher order metaprogramming, or lack thereof</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Perhaps by now you&#8217;re wondering why this article is called "Simple C&#43;&#43;11
metaprogramming", since what we covered so far wasn&#8217;t particularly simple.</p>
</div>
<div class="paragraph">
<p>The <em>relative</em> simplicity of our approach stems from the fact that we&#8217;ve not
been doing any higher order metaprogramming, that is, we haven&#8217;t introduced any
primitives that return metafunctions, such as <code>compose</code>, <code>bind</code>, or a lambda
library.</p>
</div>
<div class="paragraph">
<p>I posit that such higher order metaprogramming is, in the majority of cases,
not necessary in C&#43;&#43;11. Consider, for example, Eric Niebler&#8217;s solution given
above:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>using outer =
    typelist_cat_t&lt;
        typelist_transform_t&lt;
            typelist&lt;as_typelist_t&lt;Tuples&gt;...&gt;,
            meta_compose&lt;
                meta_quote&lt;as_typelist_t&gt;,
                meta_quote_i&lt;std::size_t, make_index_sequence&gt;,
                meta_quote&lt;typelist_size_t&gt; &gt; &gt; &gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>meta_compose</code> expression takes three other ("quoted") metafunctions and
creates a new metafunction that applies them in order. Eric uses this example
as motivation to introduce the concept of a "metafunction class" and then to
supply various primitives that operate on metafunction classes.</p>
</div>
<div class="paragraph">
<p>But when we have metafunctions <code>F</code>, <code>G</code> and <code>H</code>, instead of using
<code>meta_compose</code>, in C&#43;&#43;11 we can just do</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class... T&gt; using Fgh = F&lt;G&lt;H&lt;T...&gt;&gt;&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>and that&#8217;s it. The language makes defining composite functions easy, and there
is no need for library support. If the functions to be composed are
<code>as_typelist_t</code>, <code>std::make_index_sequence</code> and <code>typelist_size_t</code>, we just
define</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class... T&gt;
    using F = as_typelist_t&lt;std::make_index_sequence&lt;typelist_size_t&lt;T...&gt;::value&gt;&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Similarly, if we need a metafunction that will return <code>sizeof(T) &lt; sizeof(U)</code>,
there is no need to enlist a metaprogramming lambda library as in</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>lambda&lt;_a, _b, less&lt;sizeof_&lt;_a&gt;, sizeof_&lt;_b&gt;&gt;&gt;&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>We could just define it inline:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class T, class U&gt; using sizeof_less = mp_bool&lt;(sizeof(T) &lt; sizeof(U))&gt;;</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="one_more_thing">One more thing</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Finally, let me show the implementations of <code>mp_count</code> and <code>mp_count_if</code>, for
no reason other than I find them interesting. <code>mp_count&lt;L, V&gt;</code> returns the
number of occurrences of the type <code>V</code> in the list <code>L</code>; <code>mp_count_if&lt;L, P&gt;</code>
counts the number of types in <code>L</code> for which <code>P&lt;T&gt;</code> is <code>true</code>.</p>
</div>
<div class="paragraph">
<p>As a first step, I&#8217;ll implement <code>mp_plus</code>. <code>mp_plus</code> is a variadic (not just
binary) metafunction that returns the sum of its arguments.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class... T&gt; struct mp_plus_impl;

template&lt;class... T&gt; using mp_plus = typename mp_plus_impl&lt;T...&gt;::type;

template&lt;&gt; struct mp_plus_impl&lt;&gt;
{
    using type = std::integral_constant&lt;int, 0&gt;;
};

template&lt;class T1, class... T&gt; struct mp_plus_impl&lt;T1, T...&gt;
{
    static constexpr auto _v = T1::value + mp_plus&lt;T...&gt;::value;

    using type = std::integral_constant&lt;
        typename std::remove_const&lt;decltype(_v)&gt;::type, _v&gt;;
};</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now that we have <code>mp_plus</code>, <code>mp_count</code> is just</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class L, class V&gt; struct mp_count_impl;

template&lt;template&lt;class...&gt; class L, class... T, class V&gt;
    struct mp_count_impl&lt;L&lt;T...&gt;, V&gt;
{
    using type = mp_plus&lt;std::is_same&lt;T, V&gt;...&gt;;
};

template&lt;class L, class V&gt; using mp_count = typename mp_count_impl&lt;L, V&gt;::type;</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is another illustration of the power of parameter pack expansion. It&#8217;s a
pity that we can&#8217;t use pack expansion in <code>mp_plus</code> as well, to obtain</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>T1::value + T2::value + T3::value + T4::value + ...</code></pre>
</div>
</div>
<div class="paragraph">
<p>directly. It would have been nice for <code>T::value + ...</code> to have been
supported, and it appears that in C&#43;&#43;17, it will be.</p>
</div>
<div class="paragraph">
<p><code>mp_count_if</code> is similarly straightforward:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class L, template&lt;class...&gt; class P&gt; struct mp_count_if_impl;

template&lt;template&lt;class...&gt; class L, class... T, template&lt;class...&gt; class P&gt;
    struct mp_count_if_impl&lt;L&lt;T...&gt;, P&gt;
{
    using type = mp_plus&lt;P&lt;T&gt;...&gt;;
};

template&lt;class L, template&lt;class...&gt; class P&gt;
    using mp_count_if = typename mp_count_if_impl&lt;L, P&gt;::type;</code></pre>
</div>
</div>
<div class="paragraph">
<p>at least if we require <code>P</code> to return <code>bool</code>. If not, we&#8217;ll have to coerce
<code>P&lt;T&gt;::value</code> to 0 or 1, or the count will not be correct.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;bool v&gt; using mp_bool = std::integral_constant&lt;bool, v&gt;;

template&lt;class L, template&lt;class...&gt; class P&gt; struct mp_count_if_impl;

template&lt;template&lt;class...&gt; class L, class... T, template&lt;class...&gt; class P&gt;
    struct mp_count_if_impl&lt;L&lt;T...&gt;, P&gt;
{
    using type = mp_plus&lt;mp_bool&lt;P&lt;T&gt;::value != 0&gt;...&gt;;
};

template&lt;class L, template&lt;class...&gt; class P&gt;
    using mp_count_if = typename mp_count_if_impl&lt;L, P&gt;::type;</code></pre>
</div>
</div>
<div class="paragraph">
<p>The last primitive I&#8217;ll show is <code>mp_contains</code>. <code>mp_contains&lt;L, V&gt;</code> returns
whether the list <code>L</code> contains the type <code>V</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class L, class V&gt; using mp_contains = mp_bool&lt;mp_count&lt;L, V&gt;::value != 0&gt;;</code></pre>
</div>
</div>
<div class="paragraph">
<p>At first sight, this implementation appears horribly naive and inefficient&#8201;&#8212;&#8201;why would we need to count all the occurrences just to throw that away if we&#8217;re
only interested in a boolean result&#8201;&#8212;&#8201;but it&#8217;s actually pretty competitive and
perfectly usable. We just need to add one slight optimization to <code>mp_plus</code>, the
engine behind <code>mp_count</code> and <code>mp_contains</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>template&lt;class T1, class T2, class T3, class T4, class T5,
    class T6, class T7, class T8, class T9, class T10, class... T&gt;
    struct mp_plus_impl&lt;T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T...&gt;
{
    static constexpr auto _v = T1::value + T2::value + T3::value + T4::value +
        T5::value + T6::value + T7::value + T8::value + T9::value + T10::value +
        mp_plus&lt;T...&gt;::value;

    using type = std::integral_constant&lt;
        typename std::remove_const&lt;decltype(_v)&gt;::type, _v&gt;;
};</code></pre>
</div>
</div>
<div class="paragraph">
<p>This cuts the number of template instantiations approximately tenfold.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="conclusion">Conclusion</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I have outlined an approach to metaprogramming in C&#43;&#43;11 that</p>
</div>
<div class="ulist">
<ul>
<li>
<p>takes advantage of variadic templates, parameter pack expansion, and template
aliases;</p>
</li>
<li>
<p>operates on any variadic template <code>L&lt;T...&gt;</code>, treating it as its
fundamental data structure, without mandating a specific type list
representation;</p>
</li>
<li>
<p>uses template aliases as its metafunctions, with the expression <code>F&lt;T...&gt;</code>
serving as the equivalent of a function call;</p>
</li>
<li>
<p>exploits the structural similarity between the data structure <code>L&lt;T...&gt;</code>
and the metafunction call <code>F&lt;T...&gt;</code>;</p>
</li>
<li>
<p>leverages parameter pack expansion as much as possible, instead of using the
traditional recursive implementations;</p>
</li>
<li>
<p>relies on inline definitions of template aliases for function composition,
instead of providing library support for this task.</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1">
<h2 id="further_reading">Further reading</h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="simple_cxx11_metaprogramming_2.html">Part 2 is now available</a>, in which I
show algorithms that allow us to treat type lists as sets, maps, and vectors,
and demonstrate various C&#43;&#43;11 implementation techniques in the process.</p>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer-text">
Last updated 2022-04-06 21:02:40 UTC
</div>
</div>
<style>

*:not(pre)>code { background: none; color: #600000; }
/* table tr.even, table tr.alt, table tr:nth-of-type(even) { background: none; } */

</style>
</body>
</html>